package ru.spb.osll.myfit.server.handler;

import static org.junit.Assert.*;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;

import ru.spb.osll.myfit.common.Include;
import ru.spb.osll.myfit.common.Page;
import ru.spb.osll.myfit.common.Table;
import ru.spb.osll.myfit.server.parser.Constants;
import ru.spb.osll.myfit.util.CollectionUtils;

public class PageLoaderTest {

  private PageLoader pageLoader;
  @Before
  public void setUp(){
    pageLoader = EasyMock.createMockBuilder(PageLoader.class).withConstructor().addMockedMethod("readPageFile", String.class).createMock();
  }
  
  @Test
  public void testLoadSimplePage() throws IOException{
    List<String> SimpleLoadList = CollectionUtils.list("|Import|",
        "|ru.spb.osll.myfit.examples|", Constants.LINE_SEPARATOR,
        "|with cubetools|",
        "|write|1000000|files of size|0|using|80|threads|",
        Constants.LINE_SEPARATOR);
    
    EasyMock.expect(pageLoader.readPageFile("name")).andReturn(SimpleLoadList);
    EasyMock.replay(pageLoader);

    Page page = pageLoader.loadPage("name");
    assertEquals(1, page.countPageElements());
    assertTrue(page.getElement(0) instanceof Table);
    EasyMock.verify(pageLoader);
     
  }
  
  @Test
  public void testLoadPageWithInclude() throws IOException {
    List<String> SimpleLoadList = CollectionUtils.list("|Import|",
        "|ru.spb.osll.myfit.examples|", Constants.LINE_SEPARATOR,
        "|with cubetools|",
        "|write|1000000|files of size|0|using|80|threads|","!include .TestPage",
        Constants.LINE_SEPARATOR);
    
    EasyMock.expect(pageLoader.readPageFile("name")).andReturn(SimpleLoadList);
    EasyMock.replay(pageLoader);

    Page page = pageLoader.loadPage("name");
    assertEquals(2, page.countPageElements());
    assertTrue(page.getElement(0) instanceof Table);
    assertTrue(page.getElement(1) instanceof Include); 
    EasyMock.verify(pageLoader);
  }  
  
  @Test (expected=IOException.class)
  public void testNonexistentPage () throws FileNotFoundException, IOException{
    EasyMock.expect(pageLoader.readPageFile("name")).andThrow(new IOException());
    EasyMock.replay(pageLoader);

    Page page = pageLoader.loadPage("name");
    assertEquals(2, page.countPageElements());
    assertTrue(page.getElement(0) instanceof Table);
    assertTrue(page.getElement(1) instanceof Include); 
    EasyMock.verify(pageLoader);    
  }
}
